#该段代码放在research目录下运行，否在import时会出错

import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile

from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image

from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils_cumtzd_94 as vis_util

import classify_car9721 as cc

# What model to download.
FULL_PATH = '/home/cumtzd/9hw-source/models/research/object_detection/'
MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'
MODEL_FILE = FULL_PATH + MODEL_NAME + '.tar.gz'
DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'

# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = FULL_PATH + MODEL_NAME + '/frozen_inference_graph.pb'

# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join(FULL_PATH,'data', 'mscoco_label_map.pbtxt')

NUM_CLASSES = 90

def object_detect_classify(img_fn='/home/cumtzd/9hw-source/models/research/object_detection/test_images/image3.jpg'):
	if tf.__version__ < '1.4.0':
	  raise ImportError('Please upgrade your tensorflow installation to v1.4.* or later!')

	#Download Model From wwww
	'''
	opener = urllib.request.URLopener()
	opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)
	tar_file = tarfile.open(MODEL_FILE)
	for file in tar_file.getmembers():
	  file_name = os.path.basename(file.name)
	  if 'frozen_inference_graph.pb' in file_name:
	    print(file_name)
	    tar_file.extract(file, os.getcwd())
	'''

	#Load a (frozen) Tensorflow model into memory.
	detection_graph = tf.Graph()
	with detection_graph.as_default():
	  od_graph_def = tf.GraphDef()
	  with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
	    serialized_graph = fid.read()
	    od_graph_def.ParseFromString(serialized_graph)
	    tf.import_graph_def(od_graph_def, name='')
	    
	#Loading label map    
	label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
	categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
	category_index = label_map_util.create_category_index(categories)

	#Helper code
	def load_image_into_numpy_array(image):
	  (im_width, im_height) = image.size
	  return np.array(image.getdata()).reshape(
	      (im_height, im_width, 3)).astype(np.uint8)
	      
	'''#Detection
	PATH_TO_TEST_IMAGES_DIR = '/home/cumtzd/9hw-source/models/research/object_detection/test_images'
	TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(16, 17) ]'''
	
	TEST_IMAGE_PATHS = [img_fn]

	# Size, in inches, of the output images.
	IMAGE_SIZE = (24, 16) 

	with detection_graph.as_default():
	  with tf.Session(graph=detection_graph) as sess:
	    # Definite input and output Tensors for detection_graph
	    image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
	    # Each box represents a part of the image where a particular object was detected.
	    detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
	    # Each score represent how level of confidence for each of the objects.
	    # Score is shown on the result image, together with the class label.
	    detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
	    detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
	    num_detections = detection_graph.get_tensor_by_name('num_detections:0')
	    for image_path in TEST_IMAGE_PATHS:
	      image = Image.open(image_path)
	      # the array based representation of the image will be used later in order to prepare the
	      # result image with boxes and labels on it.
	      image_np = load_image_into_numpy_array(image)
	     
	      # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
	      image_np_expanded = np.expand_dims(image_np, axis=0)
	      # Actual detection.
	      (boxes, scores, classes, num) = sess.run(
		  [detection_boxes, detection_scores, detection_classes, num_detections],
		  feed_dict={image_tensor: image_np_expanded})
	      # Visualization of the results of a detection.
	      
	      vis_util.visualize_boxes_and_labels_on_image_array(
		  image_np,
		  np.squeeze(boxes),
		  np.squeeze(classes).astype(np.int32),
		  np.squeeze(scores),
		  category_index,
		  use_normalized_coordinates=True,
		  line_thickness=3)
	      od_res_img=tf.image.encode_jpeg(image_np)
	      with tf.gfile.GFile('/home/cumtzd/car_od_cls/od_output.jpg','wb') as f0:
	      	f0.write(od_res_img.eval())
        
	      #plt.figure(figsize=IMAGE_SIZE)
	      #plt.imshow(image_np) 


	#Classify
	im_width,im_height=image.size
	print(im_width,im_height)

	boxes = np.squeeze(boxes)
	classes = np.squeeze(classes).astype(np.int32)
	scores = np.squeeze(scores)   

	min_score_thresh = .5
	num_of_car = 0
	orig_image_np = load_image_into_numpy_array(image)

	for i in range(len(scores)):
		if scores[i] > min_score_thresh and classes[i]==3:
			num_of_car+=1
			box = tuple(boxes[i].tolist())
			y_min,x_min,y_max,x_max=box 
			#print(y_min,x_min,y_max,x_max)
			(left, right, top, bottom) = (x_min * im_width, x_max * im_width,y_min * im_height, y_max * im_height)
			#print(left, right, top, bottom)
			off_width,off_height,target_height,target_width=int(left),int(top),int(bottom-top),int(right-left)
			print("obj_bbox:%d,%d,%d,%d"%(off_height,off_width,target_height,target_width))
			image_raw_data = tf.gfile.FastGFile(image_path,'rb').read()
			with tf.Session() as sess2:
				img_data = tf.image.decode_jpeg(image_raw_data)
				img_data = tf.image.convert_image_dtype(img_data,dtype=tf.float32)
				cropped_img= tf.image.crop_to_bounding_box(img_data,off_height,off_width,target_height,target_width)
				    #plt.figure(figsize=IMAGE_SIZE)
				    #plt.imshow(cropped_img.eval())

				cropped_img = tf.image.convert_image_dtype(cropped_img,dtype=tf.uint8)
				encoded_image = tf.image.encode_jpeg(cropped_img)
				with tf.gfile.GFile('/home/cumtzd/tmp/car_to_classify_{}'.format(num_of_car),'wb') as f:
					f.write(encoded_image.eval())
				class_name,score,class_id=cc.run_inference_on_image('/home/cumtzd/tmp/car_to_classify_{}'.format(num_of_car))
				    
				    
				vis_util.visualize_car_boxes_and_labels_on_image_array(orig_image_np,box,class_name,score,class_id,
				                                                       use_normalized_coordinates=True,line_thickness=3)
		    
		    
	#plt.figure(figsize=IMAGE_SIZE)
	with tf.Session() as sess3:
		res_img=tf.image.encode_jpeg(orig_image_np)
		with tf.gfile.GFile('/home/cumtzd/car_od_cls/cls_output.jpg','wb') as f2:
			f2.write(res_img.eval())
		
			
	#plt.imshow(orig_image_np)
	
	if num_of_car ==0:
	    print("Can't detect any car who's score agreed 0.5 in this image! Please try other image again.")
	    
	return num_of_car
    
def main(_):
	object_detect_classify()
	return 0

if __name__ == '__main__':
  tf.app.run()
        
